/**
 * swfupload gallery style progress bar
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: progress.js 131 2013-07-24 15:56:23Z zhouyl $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
var SWFU_timer = [];

function SWFU_Progress(file, settings){
    this.file = file;
    this.progress_id = file.id;
    this.element = $('#' + this.progress_id);
    this.settings = settings;
    this.isError = false;

    if (this.file.name.length > 45) {
        this.file.name = this.file.name.substring(0, 42) + "…";
    }

    if (this.element.length <= 0) {
        var size = (this.file.size / 1024).toFixed(1);
        if (size > 1200) {
            size = (size / 1024).toFixed(1);
            if (size > 1200) {
                size = (size / 1024).toFixed(1);
                size += ' GB';
            }
            size += ' MB';
        } else {
            size += ' KB';
        }

        this.element = $(
            '<div class="item" id="' + this.file.id + '">' +
            '<div class="info">' + this.file.name + ' (' + size +') - <span><font color="gray">队列中…</font></span></div>' +
            '<div class="bar"><div class="status" style="width:0%"></div></div>' +
            '<a href="javascript:;" class="cancel"></a>' +
            '</div>'
        ).hide();

        this.element.find('a.cancel').click(function(){
            $(this).parent().remove();
        });

        this.settings.progress_target.append(this.element);
    }
}

SWFU_Progress.prototype.init = function(){
    this.element.show();
    this.settings.progress_target.show();
    return this;
};

SWFU_Progress.prototype.fadeOut = function(ms){
    var element = this.element;
    if (typeof SWFU_timer[this.progress_id] == 'number') {
        clearTimeout(SWFU_timer[this.progress_id]);
    }
    SWFU_timer[this.progress_id] = setTimeout(function(){ element.fadeOut('slow'); }, ms);
    return this;
};

SWFU_Progress.prototype.update = function(bytesLoaded){
    var percent = Math.ceil((bytesLoaded / this.file.size) * 100) + '%';
    this.element.find('.info span').html(percent);
    this.element.find('.bar .status').width(percent);
    return this;
};

SWFU_Progress.prototype.complete = function(){
    if (this.isError == false) {
        this.element.find('.info').html(this.file.name + ' &nbsp; <font color="green">(上传成功！)</font>');
        this.fadeOut(this.settings.progress_complete_time ? this.settings.progress_complete_time : 1500);
    }
    return this;
};

SWFU_Progress.prototype.error = function(message) {
    this.isError = true;
    this.element.find('.info').html(this.file.name + ' &nbsp; <font color="red">(上传失败：' + message + ')</font>');
    this.fadeOut(this.settings.progress_error_time ? this.settings.progress_error_time : 10000);
    return this;
};

SWFU_Progress.prototype.cancel = function(){
    this.element.remove();
    return this;
};